package com.ruoyi.util;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.model.FieldsDocumentPart;
import org.apache.poi.hwpf.usermodel.Field;
import org.apache.poi.hwpf.usermodel.Fields;
import org.apache.poi.hwpf.usermodel.Range;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Base64;
import java.util.Iterator;
import java.util.Map;

public class FileUtil {
    public static void writeWord(Map<String,String> map,String filePath,String targetFileName,String generateFileName){
        //读取word模板
//        String fileDir = new File(base.getFile(),"http://www.cnblogs.com/http://www.cnblogs.com/../doc/").getCanonicalPath();
        FileInputStream in = null;
        try {
            in = new FileInputStream(new File(filePath+targetFileName));
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        HWPFDocument hdt = null;
        try {
            hdt = new HWPFDocument(in);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        Fields fields = hdt.getFields();
        Iterator<Field> it = fields.getFields(FieldsDocumentPart.MAIN).iterator();

        //读取word文本内容
        Range range = hdt.getRange();
        //替换文本内容
        for (Map.Entry<String,String> entry: map.entrySet()) {
            if(entry.getValue() == null){
                range.replaceText("$" + entry.getKey() + "$","");
            }else{
                range.replaceText("$" + entry.getKey() + "$",entry.getValue());
            }
        }
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(filePath+generateFileName,true);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            hdt.write(ostream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //输出字节流
        try {
            out.write(ostream.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            ostream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void downFile(String url, String fileName, HttpServletResponse response){
        try {
            File file = new File(url);
            response.reset();
            response.setContentType("bin");
            response.setHeader("Content-Disposition","attachment; filename=\"" + new String(fileName.getBytes("GBK"), "ISO8859_1") + "\"");
            OutputStream out = response.getOutputStream();
            FileInputStream fis = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fis.read(data);
            fis.close();
            out.write(data);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
	public static void stringToTxt(String bufferStr,String path){

        try{
            File file = new File(path);
            if(!file.exists()){
                file.createNewFile();
            }
//			BufferedWriter output = new BufferedWriter(new FileWriter(file));
            BufferedWriter output = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (file,true),"UTF-8"));
            output.write(bufferStr);
            output.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static String base64ToJpg(String path,String base64,String date,String suffix){
        // 判断文件路径是否存在
        File filePath = new File(path);
        if (!filePath.exists()){
            filePath.mkdirs();
        }
        // 创建文件
        String jpgFile = path + "\\" + date + "." + suffix;
        File file = new File(jpgFile);
        boolean jpgFileExist = false;
        try {
            jpgFileExist = file.createNewFile();
            System.out.println(suffix+"文件创建成功");
        } catch (IOException e) {
            System.out.println(suffix+"文件创建失败");
            e.printStackTrace();
        }
        if (jpgFileExist){
            // 解密
            Base64.Decoder decoder = Base64.getDecoder();
            // 去掉base64前缀 data:image/jpeg;base64,
            base64 = base64.substring(base64.indexOf(",", 1) + 1, base64.length());
            byte[] b = decoder.decode(base64);
            // 处理数据
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            // 保存图片
            try {
                FileOutputStream out = new FileOutputStream(jpgFile);
                out.write(b);
                out.flush();
                out.close();
                // 写入成功返回文件路径
                return jpgFile;
            } catch (FileNotFoundException e) {
                System.out.println("文件未找到");
                e.printStackTrace();
            } catch (IOException e) {
                System.out.println("写入失败");
                e.printStackTrace();
            }
        }
        return "文件不存在";
    }
}
